package com.gopay.cashier.service.security.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.gopay.cashier.dao.CertFreeQuotaDao;
import com.gopay.cashier.service.security.GopayDtCertService;
import com.gopay.common.security.vo.DtCertCheckParamVO;
import com.gopay.common.security.vo.DtCertCheckResultVO;
import com.gopay.common.security.vo.UserDtCertInfoVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.gopay.common.domain.cust.CustCertFreeQuota;
import com.gopay.common.domain.cust.CustPersonInfo;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.user.dao.CustPersonInfoQueryDAO;
import com.gopay.remote.scs.cert.CertCheckRemoteService;
import com.gopay.remote.scs.dt.DtCheckRemoteService;
import com.gopay.remote.scs.vo.DtCertCheckResponse;

/**
 * 国付宝动态令牌和数字证书服务类
 * 
 * @GopayDtCertService.java
 * @author fanghw
 * @2016年9月22日 下午3:23:41  www.gopay.com.cn Inc.All rights reserved.
 */
@Service("gopayDtCertService")
public class GopayDtCertServiceImpl implements GopayDtCertService {

    private static final String SESSION_UUID_KEY="CERTUUIDKEY";

    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;

    @Resource(name = "custPersonInfoQueryDao")
    private CustPersonInfoQueryDAO custPersonInfoQueryDao;

    @Resource(name="certFreeQuotaDao")
    CertFreeQuotaDao certFreeQuotaDao;



    @Resource(name = "certCheckRemoteService")
    private CertCheckRemoteService certCheckRemoteService;

    @Resource(name = "dtCheckRemoteService")
    private DtCheckRemoteService dtCheckRemoteService;

    @Override
    public UserDtCertInfoVO getOnOffAndCertSN(String userId) {
        UserDtCertInfoVO retVo=new UserDtCertInfoVO();

        //封装SQL
        StringBuilder sql=new StringBuilder();
        sql.append(" select u.user_id, ");
        sql.append(" u.user_type, ");
        sql.append(" u.oper_id, ");
        sql.append(" ce.sn, ");
        sql.append(" decode(c.DYN_PWD_SWITCH,'01','1','0') dt_switch, ");
        sql.append(" decode(c.CA_CERT_SWITCH,'01','1','0') cert_switch, ");
        sql.append(" fq.quota ");
        sql.append(" from user_info u ");
        sql.append(" left join gopay_all_cust_info c on c.cust_id=u.cust_id ");
        sql.append(" left join cust_ca_cert ce on (ce.user_id=u.user_id and ce.cert_type='01' and ce.stat='01') ");
        sql.append(" left join cust_cert_free_quota fq on (fq.cust_id=u.cust_id and fq.stat='01') ");

        sql.append(" where u.user_id=:userId ");

        //封装参数
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);

        // 执行查询
        List<Object[]> rsList = commonQueryDAO.findBySql(sql.toString(), map);
        String sns="";
        if(rsList!=null){
            String sn,dtSwitch,certSwitch;
            for (Object[] arr : rsList) {
                sn=(String)arr[3];
                dtSwitch=(String)arr[4];
                certSwitch=(String)arr[5];

                //
                if(StringUtils.isNotBlank(sn)&&!sns.contains(sn)){
                    if(StringUtils.isNotBlank(sns)){
                        sns+=",";
                    }
                    sns+=sn;
                }

                //
                if("1".equals(dtSwitch)){
                    retVo.setDtSwitch(true);
                }

                if("1".equals(certSwitch)){
                    retVo.setCertSwitch(true);
                }

                if(arr[6]!=null){
                    retVo.setFreeQuota(((BigDecimal) arr[6]).setScale(2, RoundingMode.HALF_UP).toString());
                }
            }
            retVo.setSns(sns);
        }



        return retVo;
    }

    @Override
    public String getUUID(HttpServletRequest request) {
        String uuid = createUUID();
        request.getSession().setAttribute(SESSION_UUID_KEY, uuid);

        return uuid;
    }

    private String createUUID() {
        // 生成随机数
        String uuid = UUID.randomUUID().toString().replaceAll("@", "");
        uuid = uuid.replaceAll("-", "0");
        if (uuid.length() >= 32) {
            uuid = uuid.substring(0, 32);
        } else {
            uuid += "0123456789abcdef0123456789abcdef".substring(0, 32 - uuid.length());
        }
        return uuid;
    }


    public DtCertCheckResultVO checkDtCert(HttpServletRequest request, DtCertCheckParamVO paramVo){
        DtCertCheckResultVO resultVo=new DtCertCheckResultVO();

        //校验令牌和证书的总开关
        UserDtCertInfoVO onoff =getOnOffAndCertSN(paramVo.getUserId());

        //个人免验证额度判断,只针对有交易金额的校验
        if(paramVo.getTranAmt()!=null){
            CustPersonInfo personInfo=custPersonInfoQueryDao.getByCustId(paramVo.getCustId());
            if(personInfo!=null){
                CustCertFreeQuota freeQuota=certFreeQuotaDao.find(CustCertFreeQuota.class, paramVo.getCustId());
                //判断额度状态是否开启
                if(freeQuota!=null&&"01".equals(freeQuota.getStat())){
                    if(onoff.isDtSwitch()&&"02".equals(freeQuota.getCertType())
                            &&paramVo.getTranAmt().compareTo(freeQuota.getQuota())<=0){
                        //不校验动态口令
                        onoff.setDtSwitch(false);;
                    }
                    if(onoff.isCertSwitch()&&"01".equals(freeQuota.getCertType())
                            &&paramVo.getTranAmt().compareTo(freeQuota.getQuota())<=0){
                        //不校验数字证书
                        onoff.setCertSwitch(false);;
                    }
                }
            }
        }


        if(onoff.isDtSwitch()){
            //通过第三方系统校验动态令牌
            resultVo=checkDtByTPS(paramVo);
        }else if(onoff.isCertSwitch()){
            //通过第三方系统校验数字证书
            resultVo=checkCertByTPS(request,paramVo);
        }else{
            //默认为校验成功
            resultVo.setSuccess(true);
        }

        return resultVo;

    }

    /**
     * 通过第三方系统校验动态令牌
     * @param paramVo
     * @return
     */
    private DtCertCheckResultVO checkDtByTPS(DtCertCheckParamVO paramVo){
        //校验动态令牌
        DtCertCheckResponse resp=dtCheckRemoteService.checkDt(paramVo.getUserId(), paramVo.getDtCode());

        //封装返回结果
        DtCertCheckResultVO resultVo=new DtCertCheckResultVO();
        resultVo.setSuccess(resp.isSuccess());
        resultVo.setErrCode(resp.getErrCode());
        resultVo.setErrMsg(resp.getErrMsg());

        return resultVo;
    }

    /**
     * 通过第三方系统校验数字证书
     * @param request
     * @param paramVo
     * @return
     */
    private DtCertCheckResultVO checkCertByTPS(HttpServletRequest request, DtCertCheckParamVO paramVo){
        String uuid=(String)request.getSession().getAttribute(SESSION_UUID_KEY);
        //删除session，保证一次一用
        request.getSession().removeAttribute(SESSION_UUID_KEY);

        //恶意字符加号回显
        paramVo.setCertSignValue(paramVo.getCertSignValue().replaceAll("_EVIL_CHAR_PLUS_", "+"));

        //校验证书
        DtCertCheckResponse resp=certCheckRemoteService.checkCert(paramVo.getUserId(),uuid, paramVo.getCertSignValue());

        //封装返回结果
        DtCertCheckResultVO resultVo=new DtCertCheckResultVO();
        resultVo.setSuccess(resp.isSuccess());
        resultVo.setErrCode(resp.getErrCode());
        resultVo.setErrMsg(resp.getErrMsg());

        return resultVo;
    }

    @Override
    public void checkPayPwd(HttpServletRequest request, String custId, String payPwd) {
        // TODO Auto-generated method stub

    }

    @Override
    public void checkLoginPwd(HttpServletRequest request, String userId, String loginPwd) {
        // TODO Auto-generated method stub

    }
    
}
